var mongoose = require('mongoose');
var model = require('../model');
var config = require('../config');

var Manager = model.Manager;

//＃ 需要管理员登录
//
exports.managerRequired = function(req, res, next) {
    if (!req.session || !req.session.manager) {
        res.redirect('/backend/login');
        return;
    }
    next();
};


//＃ 生成管理员session
//
exports.generateManagerSession = function(manager, res) {
    var auth_token = manager._id + '$$$$'; //以后可能会存储更多信息，用 $$$$ 来分隔
    var opts = {
        path: '/',
        maxAge: 1000 * 60 * 60 * 24 * 30, //cookie 有效期30天
        signed: true,
        httpOnly: true
    };
    res.cookie(config.cookie_backend, auth_token, opts);
};

// 验证用户是否登录
exports.authManager = function(req, res, next) {
    res.locals.current_manager = null;

    if (req.session.manager) {
        if (!req.session.manager) {
            return next();
        }
        res.locals.current_manager = req.session.manager;
        next();
    } else {
        var auth_token = req.signedCookies[config.cookie_backend];
        if (!auth_token) {
            return next();
        }
        var auth = auth_token.split('$$$$');
        var managerId = auth[0];
        Manager.findOne({
            _id: managerId
        }, function(error, manager) {
            if (error) {
                console.log(error);
                return;
            } else {
                if (!manager) {
                    return next();
                }
                res.locals.current_manager = req.session.manager = manager;
                next();
            }

        });
    }
};